// 模拟数据库
const users = new Map();
const callHistory = [];

export const login = async (ctx) => {
  try {
    const { username, password } = ctx.request.body;
    // 简单的用户验证逻辑
    const userId = `user-${Date.now()}`;
    users.set(userId, { username, password });

    ctx.message = '登录成功';
    ctx.body = {
      userId,
      username,
      token: `dummy-token-${userId}`
    };
  } catch (error) {
    ctx.status = 400;
    ctx.message = '登录失败';
    throw error;
  }
};

export const getOnlineUsers = async (ctx) => {
  try {
    // 这里应该从 socket 实例获取在线用户
    ctx.body = Array.from(users.entries()).map(([id, user]) => ({
      userId: id,
      username: user.username
    }));
  } catch (error) {
    ctx.status = 500;
    ctx.message = '获取在线用户失败';
    throw error;
  }
};

export const createCall = async (ctx) => {
  try {
    const { targetId } = ctx.request.body;
    const callId = `call-${Date.now()}`;
    
    // 记录通话
    callHistory.push({
      id: callId,
      from: ctx.state.user.id,
      to: targetId,
      startTime: new Date(),
      status: 'initiated'
    });

    ctx.status = 201;
    ctx.message = '通话创建成功';
    ctx.body = { callId };
  } catch (error) {
    ctx.status = 400;
    ctx.message = '创建通话失败';
    throw error;
  }
};

export const getCallHistory = async (ctx) => {
  try {
    ctx.body = { calls: callHistory };
  } catch (error) {
    ctx.status = 500;
    ctx.message = '获取通话历史失败';
    throw error;
  }
};
